var nodeAnidata = [];
var matAnidata = [];
var keyArray = [];
var flag = true;
function loadAnimation(filename){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', filename, true);
  xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
          var data = xhr.response;
          for (var i = 0; i < data["nodes"].length; i++) {
              if (data["nodes"][i]["animation"]) {
                nodeAnidata.push(data["nodes"][i]);
              }
          }
          for (var i = 0; i < data["materials"].length; i++) {
              if (data["materials"][i]["animation"]) {
                matAnidata.push(data["materials"][i]);
              }
          }
      }

  };
  xhr.responseType = 'json';
  xhr.send();
}

function getObjectByMaterialName(value) {
  if ( this.material && this.material.name === value ) 
    return this;
  if(this.material){
    //console.log(this.material.name);
    //console.log(this.material);
  }
  for ( var i = 0, l = this.children.length; i < l; i ++ ) {
    var child = this.children[ i ];
    var object = getObjectByMaterialName.call(child,value );
    if ( object !== undefined ) {
      return object;
    }
  }
  return undefined;
}


function startKeyAnimation(scene,node,start,end,time,repeat,delay,yoyo,reverse) {
  //调用动画
  //70
  //console.log(nodeAnidata);
  //console.log(matAnidata);
  for (var i = 0; i < nodeAnidata.length; i++) {
    var object = scene.getObjectByName(nodeAnidata[i]["nodename"], true );
    if(object)
      startAnimation("node",object,nodeAnidata[i],start,end,time,repeat,delay,yoyo,reverse);
  }

  for (var i = 0; i < matAnidata.length; i++) {
    var object = getObjectByMaterialName.call(node,matAnidata[i]["materialname"]);
    if(object)
      startAnimation("mat",object.material,matAnidata[i],start,end,time,repeat,delay,yoyo,reverse);
  }
}

function startAnimation(type,node,anidata,start,end,time,repeat,delay,yoyo,reverse) {
    if (name == null)  name = "";
    if (start == null) start = 0;
    if (end == null)   end = 0;
    if (time == null)  time = 0;
    if (repeat == null) repeat = 0;
    if (delay == null)  delay = 0;
    if (yoyo == null) yoyo = false;
    if (reverse == null) reverse = false;

    if(!node){
      return;
    }

    var maxframe = Math.abs(end);

    var count = 0;
    var posArray = [];
    var rotArray = [];
    var scaleArray = [];


    
    var channelData = {};
    var channelValueFirst = {};
    var channelValue = [];
    var channelFN = {};

    function addKFtoChannel(kfindex,frameNo,name,value,inter,ease){

      if(!channelFN[name]){
        channelFN[name] = [];
        channelFN[name+'inter'] = [];
        channelFN[name+'ease'] = [];
      }

      var frameradio = frameNo/(maxframe+1);
      //if(frameradio > 1.0)
      //  frameradio = 1.0;
      channelFN[name].push(frameradio);
      channelFN[name+'inter'].push(inter);
      channelFN[name+'ease'].push(ease);

      if(kfindex == 0){
        channelValueFirst[name] = value;
        return;
      }

      if(!channelValue[kfindex - 1]){
        channelValue[kfindex - 1] = {};
      }
      //console.log(kfindex-1,name,value)
      channelValue[kfindex - 1][name] = value;
    }

                  
    var nodeAni = anidata["animation"]["curves"];
    //console.log(nodeAni.length);
    for (var  j= 0; j < nodeAni.length; j++) {

        var channel = nodeAni[j];
        //console.log(channel);
        var name = channel.datatype;
        if(name == "texture_slots[0].alpha_factor"){
          name = "alpha";
        }
        var index = channel.arrayindex;
        var kf = channel.keyframepoints;

        var channelName = name+index;
        //console.log(channelName)
        channelData[channelName] = 1.0;
        for(var k = 0; k < kf.length/2; k++ ){
            var frameNo = kf[k*4+0];
            var value = kf[k*4+1];
            var inter = kf[k*4+2];
            var ease = kf[k*4+3];
            if(frameNo >= 0){
              addKFtoChannel(k,frameNo,channelName,value,inter,ease);
            }
        }
      count ++;
    }
    var startTime = time/end*start*1000;
    if(start == 0 || start == 1)
      startTime = null;
    JT.fromTo(channelData, time, channelValueFirst,{
        through : channelValue,
        channelFN:channelFN,
        startTime:startTime,
        reverse:reverse,
        delay: delay,
        repeat: repeat,
        yoyo: yoyo,
        //ease: JT.Bounce.InOut,
        //ease:JT.Linear.None,
        onUpdate: function (arguments) {

            if(this.curVars.location0){
              node.position.x = this.curVars.location0.num;
            }
            if(this.curVars.location1){
              //console.log(this.curVars.location1.num);
              node.position.y = this.curVars.location1.num;
            }
            if(this.curVars.location2){
              node.position.z = this.curVars.location2.num;
            }
            if(this.curVars.rotation_euler0){
              node.rotation.x = this.curVars.rotation_euler0.num;
              node.rotation.order = 'ZYX';
            }
            if(this.curVars.rotation_euler1){
              node.rotation.y = this.curVars.rotation_euler1.num;
              node.rotation.order = 'ZYX';
            }
            if(this.curVars.rotation_euler2){
              node.rotation.z = this.curVars.rotation_euler2.num;
              node.rotation.order = 'ZYX';
            }
            if(this.curVars.scale0){
              node.scale.x = this.curVars.scale0.num;
            }
            if(this.curVars.scale1){
              node.scale.y = this.curVars.scale1.num;
            }
            if(this.curVars.scale2){
              node.scale.z = this.curVars.scale2.num;
            }
            if(this.curVars.diffuse_color0){
              node.color.r = this.curVars.diffuse_color0.num;
            }
            if(this.curVars.diffuse_color1){
              node.color.g = this.curVars.diffuse_color1.num;
            }
            if(this.curVars.diffuse_color2){
              node.color.b = this.curVars.diffuse_color2.num;
            }

            if(this.curVars.alpha0){
              node.opacity = this.curVars.alpha0.num;
            }
        }
    });
}
